October 4
2018
August 11
2017
Install PHP MVC Frameworks with Composer
CodeIgniter
# Create skeleton project composer create-project kenjis/codeigniter-composer-installer <project-name> # Run PHP built-in server cd <project-name> bin/server.sh
Laravel (installer)
# Method 1: Install Laravel installer globally composer global require "laravel/installer=~1.1" # Create Laravel project with installer laravel new <project-name> # Run PHP built-in server cd <project-name> php -S localhost:8000 -t <project-name>/public <project-name>/server.php
Laravel (GitHub)
# Get latest version from GitHub cd /var/www/ git clone https://github.com/laravel/laravel.git # Navigate to Laravel folder and install dependencies cd /var/www/laravel composer install # Set app permissions chown -R apache:apache /var/www/laravel chmod -R 755 /var/www/laravel # Generate new application key cd /var/www/laravel mv .env.example .env php artisan key:generate # Verify new key cat /var/www/laravel/.env # Create new Apache virtual host file for the laravel app nano /etc/httpd/conf/httpd.conf <Directory /var/www/laravel/public> Options All AllowOverride All Order Allow,Deny Allow from all </Directory>
Symfony
# Create skeleton project composer create-project symfony/framework-standard-edition <project-name> # Run PHP built-in server cd <project-name> php bin/console server:run
Zend Framework
# Global install composer require --dev zendframework/zend-component-installer
May 11
2017
Check for PHP in CLI
March 30
2017
Check Remote File
With CURL
function checkRemoteFile($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); // Don't download content curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if(curl_exec($ch)!==FALSE) { return true; } else{ return false; } }
Without CURL
function is_webfile($webfile) { $fp = @fopen($webfile, "r"); if ($fp !== false) { fclose($fp); return true; } else { return false; } }
November 9
2016
Image Resizer in PHP
Create Image Resizer in PHP
<?php /** * Credits: Bit Repository * Source URL: http://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html */ class Resize_Image { var $image_to_resize; var $new_width; var $new_height; var $ratio; var $new_image_name; var $save_folder; function resize() { $info = GetImageSize($this->image_to_resize); if(empty($info)) { exit("The file ".$this->image_to_resize." doesn't seem to be an image."); } $width = $info[0]; $height = $info[1]; $mime = $info['mime']; /* Keep Aspect Ratio? */ if($this->ratio) { // if preserving the ratio, only new width or new height // is used in the computation. if both // are set, use width if (isset($this->new_width)) { $factor = (float)$this->new_width / (float)$width; $this->new_height = $factor * $height; } else if (isset($this->new_height)) { $factor = (float)$this->new_height / (float)$height; $this->new_width = $factor * $width; } else { exit("neither new height or new width has been set"); } } // Get image type $type = substr(strrchr($mime, '/'), 1); switch ($type) { case 'jpeg': $image_create_func = 'ImageCreateFromJPEG'; $image_save_func = 'ImageJPEG'; $new_image_ext = 'jpg'; break; case 'png': $image_create_func = 'ImageCreateFromPNG'; $image_save_func = 'ImagePNG'; $new_image_ext = 'png'; break; case 'bmp': $image_create_func = 'ImageCreateFromBMP'; $image_save_func = 'ImageBMP'; $new_image_ext = 'bmp'; break; case 'gif': $image_create_func = 'ImageCreateFromGIF'; $image_save_func = 'ImageGIF'; $new_image_ext = 'gif'; break; case 'vnd.wap.wbmp': $image_create_func = 'ImageCreateFromWBMP'; $image_save_func = 'ImageWBMP'; $new_image_ext = 'bmp'; break; case 'xbm': $image_create_func = 'ImageCreateFromXBM'; $image_save_func = 'ImageXBM'; $new_image_ext = 'xbm'; break; default: $image_create_func = 'ImageCreateFromJPEG'; $image_save_func = 'ImageJPEG'; $new_image_ext = 'jpg'; } // New Image $image_c = ImageCreateTrueColor($this->new_width, $this->new_height); $new_image = $image_create_func($this->image_to_resize); ImageCopyResampled($image_c, $new_image, 0, 0, 0, 0, $this->new_width, $this->new_height, $width, $height); if($this->save_folder) { if($this->new_image_name) { $new_name = $this->new_image_name.'.'.$new_image_ext; } else { $new_name = basename($this->image_to_resize); $new_name = $this->new_thumb_name($new_name).'_resized.'.$new_image_ext; } $save_path = $this->save_folder.$new_name; } else { /* Show the image without saving it to a folder */ header("Content-Type: ".$mime); $image_save_func($image_c); $save_path = ''; } $process = $image_save_func($image_c, $save_path); return array('result' => $process, 'new_file_path' => $save_path); } function new_thumb_name($filename) { $string = trim($filename); $string = strtolower($string); $string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string)); $string = ereg_replace("[ tnr]+", "_", $string); $string = str_replace(" ", '_', $string); $string = ereg_replace("[ _]+", "_", $string); return $string; } } ?>
September 27
2016
Regular Expressions
Regular Expression Testers
Online: http://www.phpliveregex.com/ http://regexr.com/ Offline: https://github.com/gskinner/regexr
Search for PHP Short Tag <?
<\?(?!php)(?!xml)
YouTube URL Patterns
RegEx: ^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&"'>]+) Flag: gm PHP Function: /** * Get Youtube video ID from URL * * @param string $url * @return mixed Youtube video ID or FALSE if not found * * How to use * if ($url) { * $youtube = getYoutubeIdFromUrl($url); * if (!$youtube) { * $vid = $url; * } else { * $vid = 'https://www.youtube.com/embed/'.$youtube; * } * echo "View Video »"; * } */ function getYoutubeIdFromUrl($url) { $pattern = '#^(?:https?://)?(?:www\.)?(?:m\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x'; preg_match($pattern, $url, $matches); return isset($matches[1]) ? $matches[1] : false; } Search Strings: Here
UK Phone Patterns
RegEx 1 (Relax, allow phone number started with digit, ( or +, contains (, ), +, ' ', and any digit length between 6 to 20): ^[0-9\+\(][\+\(\)\s0-9]{5,20}$ RegEx 2 (Relax, allow phone number which contains at least 6 digits): ^\D*(?:\d\D*){6,}$ RegEx 3 (Strict): ^(\+?44)?(\(\d+\))?[\d ]+(#\d+)?
July 14
2016
Website Performance
Deferred parsing of Javascript – General
<script type="text/javascript">
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else
window.onload = downloadJSAtOnload;
</script>
Deferred parsing of JavaScript in WordPress
// Defer Javascript parsing. Add this to the theme's functions.php function defer_parsing_of_js ($url) { if (false === strpos($url, '.js')) return $url; if (strpos($url, 'jquery.js')) return $url; // return '$url async onload=myinit()'; return '$url defer '; } add_filter('clean_url', 'defer_parsing_of_js', 11, 1);
Lazy CSS Loading with JavaScript
<script> var cb = function() { var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = 'yourCSSfile.css'; var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h); }; var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame; if (raf) raf(cb); else window.addEventListener('load', cb); </script>
Modify .htaccess to Leverage Browser Caching
# ---------------------------------------------------------------------- # | Leverage Browser Caching | # ---------------------------------------------------------------------- ## EXPIRES CACHING ## <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType text/html "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 1 month" </IfModule> ## EXPIRES CACHING ## ## CACHE CONTROL BY HTTP HEADERS ## Header unset Pragma <IfModule mod_headers.c> <FilesMatch "\\.(ico|jpe?g|png|gif|flv|svg|swf)$"> Header set Cache-Control "max-age=2692000, public" </FilesMatch> <FilesMatch "\\.(css)$"> Header set Cache-Control "max-age=2692000, public" </FilesMatch> <FilesMatch "\\.(js)$"> Header set Cache-Control "max-age=216000, private" </FilesMatch> <FilesMatch "\\.(x?html?|php)$"> Header set Cache-Control "max-age=600, private, must-revalidate" </FilesMatch> # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Remove `ETags` as resources are sent with far-future expires headers Header unset ETag Header unset Last-Modified </IfModule> # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # `FileETag None` doesn't work in all cases. FileETag None ## CACHE CONTROL BY HTTP HEADERS ##
Modify .htaccess to enable Compression
# ---------------------------------------------------------------------- # | Compression | # ---------------------------------------------------------------------- <IfModule mod_deflate.c> # Force compression for mangled `Accept-Encoding` request headers <IfModule mod_setenvif.c> <IfModule mod_headers.c> SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding </IfModule> </IfModule> # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Compress all output labeled with one of the following media types. # (!) For Apache versions below version 2.3.7 you don't need to # enable `mod_filter` and can remove the `<IfModule mod_filter.c>` # and `</IfModule>` lines as `AddOutputFilterByType` is still in # the core directives. <IfModule mod_filter.c> AddOutputFilterByType DEFLATE "application/atom+xml" \ "application/javascript" \ "application/json" \ "application/ld+json" \ "application/manifest+json" \ "application/rdf+xml" \ "application/rss+xml" \ "application/schema+json" \ "application/vnd.geo+json" \ "application/vnd.ms-fontobject" \ "application/x-font-ttf" \ "application/x-javascript" \ "application/x-web-app-manifest+json" \ "application/xhtml+xml" \ "application/xml" \ "font/eot" \ "font/opentype" \ "image/bmp" \ "image/svg+xml" \ "image/vnd.microsoft.icon" \ "image/x-icon" \ "text/cache-manifest" \ "text/css" \ "text/html" \ "text/javascript" \ "text/plain" \ "text/vcard" \ "text/vnd.rim.location.xloc" \ "text/vtt" \ "text/x-component" \ "text/x-cross-domain-policy" \ "text/xml" </IfModule> # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Map the following filename extensions to the specified # encoding type in order to make Apache serve the file types # with the appropriate `Content-Encoding` response header # (do note that this will NOT make Apache compress them!). # # If these files types would be served without an appropriate # `Content-Enable` response header, client applications (e.g.: # browsers) wouldn't know that they first need to uncompress # the response, and thus, wouldn't be able to understand the # content. <IfModule mod_mime.c> AddEncoding gzip svgz </IfModule> </IfModule> <FilesMatch "\\.(js|css|html|htm|php|xml)$"> SetOutputFilter DEFLATE </FilesMatch> <IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </IfModule>
Prevent Image Hotlinking
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC] RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourotherwebsite.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ http://i.imgur.com/MlQAH71.jpg [NC,R,L]
Allow Caching with HTTP Headers
// Allow cache in HTTP headers function frontend_http_headers_with_cache() { if(!is_admin()) { header_remove("Cache-Control"); header("Cache-Control: public, max-age=1200"); } } add_action('send_headers', 'frontend_http_headers_with_cache', 10, 1);
MySQL Query Cache
# Check if query cache is available show variables like 'have_query_cache'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | have_query_cache | YES | +------------------+-------+ # Check query cache variables show variables like 'query%'; +------------------------------+---------+ | Variable_name | Value | +------------------------------+---------+ | query_alloc_block_size | 8192 | | query_cache_limit | 1048576 | | query_cache_min_res_unit | 4096 | | query_cache_size | 8388608 | | query_cache_type | ON | | query_cache_wlock_invalidate | OFF | | query_prealloc_size | 8192 | +------------------------------+---------+ # Enable query cache in my.cnf query_cache_size = 268435456 query_cache_type = 1 query_cache_limit = 1048576
suPHP vs mod_php
suPHP – for each request the web server opens a new thread on behalf of that user mod_php – every request is processed on web server behalf Pros: suPHP – the web server can be … threaded safe, and it is separated from php – can be isolated based on user/environment mod_php – you can use php_value and other php settings right from .htaccess – it is way faster than suPHP Cons: suPHP – you can’t use php_value and other php settings from .htaccess – slower – higher response time – higher CPU load mod_php – PHP safe mode it is not quite safe – higher memory consumption than suPHP – can’t be isolated based on user/environment
December 11
2015